package com.cat.controller;

import com.cat.execption.DaoExecption;
import com.cat.pojo.Student;
import com.cat.service.Impl.StudentServiceImpl;
import com.cat.util.ServletUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

import static com.cat.util.ServletUtils.showError;

/**
 * @author :HYC  email: kobe524348@gmail.com
 * @program : HYC_CatRecruit
 * @name : AdminServlet
 * @description : A servlet to deal with admin request
 * @create : 2019-03-26 20:34
 */
@WebServlet(value = "/AdminServlet")
public class AdminServlet extends HttpServlet {
    StudentServiceImpl serv = new StudentServiceImpl();
    HttpSession sess = null;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        sess = req.getSession();
        String method = req.getParameter("method");
        System.out.println("com.cat.controler.adminservlet : method is " + method);
        if ("admin".equalsIgnoreCase(method)) {
            if (sess.getAttribute("studentMap") != null) {
                //从session中获取学生表并转发到jsp页面展示
                System.out.println("com.cat.controler.AdminServlet : set attr from session");
                req.setAttribute("studentMap", sess.getAttribute("studentMap"));
                req.getRequestDispatcher("allstudent.jsp").forward(req, res);
            } else {
                System.out.println("com.cat.controler.AdminServlet : redirect to method \"all\"");
                res.sendRedirect("AdminServlet?method=all");
            }
        } else if ("all".equalsIgnoreCase(method)) {
            if (getAllStudents(req, res)) {
                req.getRequestDispatcher("allstudent.jsp").forward(req, res);
            } else {
                req.setAttribute("message", "fail to get all students info");
                req.getRequestDispatcher("error.jsp").forward(req, res);
            }
        } else if ("delete".equalsIgnoreCase(method)) {
            if (deleteStudent(req, res)) {
                res.sendRedirect("AdminServlet?method=admin");
            } else {
                req.setAttribute("message", "fail to delete");
                req.getRequestDispatcher("error.jsp").forward(req, res);
            }
        } else if ("修改".equalsIgnoreCase(method)) {
            if (updateStudent(req, res)) {
                if (sess.getAttribute("admin") != null) {
                    res.sendRedirect("AdminServlet?method=admin");
                } else {
                    res.sendRedirect("StudentServlet?method=update");
                }
            } else {
                showError(req, res, "修改错误 ：无法修改学生信息", "解决方案 ： 当您看到此条信息，服务器已经发生严重故障，请与管理员联系处理此问题");
            }
        } else if ("取消".equalsIgnoreCase(method)) {
                if (sess.getAttribute("admin") != null) {
                    req.setAttribute("update", "do");
                    res.sendRedirect("AdminServlet?method=admin");
                } else {
                    res.sendRedirect("StudentServlet?method=update");
                }
//                showError(req, res, "修改错误 ：无法修改学生信息", "解决方案 ： 当您看到此条信息，服务器已经发生严重故障，请与管理员联系处理此问题");
//            res.sendRedirect("AdminServlet?method=admin");
        } else if ("update".equalsIgnoreCase(method)) {
            req.getRequestDispatcher("AdminServlet?method=admin&update=do").forward(req, res);
        } else if ("搜索".equalsIgnoreCase(method)) {
            if (findStudent(req, res)) {
                req.setAttribute("studentMap", sess.getAttribute("studentMap"));
                req.getRequestDispatcher("allstudent.jsp").forward(req, res);
            } else {
                showError(req, res, "搜索错误: 没有找到符合条件的学生", "解决方案：请检查您的条件输入是否正确");
            }
        }
    }

    private boolean findStudent(HttpServletRequest req, HttpServletResponse res) {
        System.out.println("com.cat.controler.AdminServlet : to get find students ");
        List<Student> list = serv.findStudent(req.getParameter("attr"), req.getParameter("value"));
        if (list.size() > 0) {
            req.setAttribute("studentMap", list);
            //更新session
            sess.setAttribute("prePage", "search");
            sess.setAttribute("studentMap", list);
            System.out.println("com.cat.controler.AdminServlet : return students by search successfully !");
            return true;
        } else {
            return false;
        }
    }

    /**
     * @Description: to delete a student by request parameter "delete"
     * @Param: [req, res]
     * @return: boolean
     * @Author: HYC email:kobe524348@gmail.com
     * @Date: 2019/3/27
     */
    private boolean deleteStudent(HttpServletRequest req, HttpServletResponse res) {
        String stuId = req.getParameter("stuId");
        Student stu = new Student();
        stu.setStudentId(stuId);
        try {
            serv.deleteStudent(stu);
        } catch (DaoExecption daoExecption) {
            daoExecption.printStackTrace();
            return false;
        }
        //更新session中的学生表为当前数据库的所有学生
        getAllStudents(req, res);
        return true;
    }


    private boolean getAllStudents(HttpServletRequest req, HttpServletResponse res) {

        System.out.println("com.cat.controler.AdminServlet : to get all students ");
        List<Object> list = serv.getAllStudents();
        if (list.size() > 0) {
            req.setAttribute("studentMap", list);
            //更新session
            sess.setAttribute("studentMap", list);
            System.out.println("com.cat.controler.AdminServlet : return all students successfully !");
            return true;
        } else {
            return false;
        }
    }

    /**
     * @Description: to update a student info
     * @Param: [req, res]
     * @return: boolean
     * @Author: HYC email:kobe524348@gmail.com
     * @Date: 2019/3/28
     */
    private boolean updateStudent(HttpServletRequest req, HttpServletResponse res) {
        System.out.println("com.cat.controler.AdminServlet : to update student info...");
        Student stu = ServletUtils.Mapping2Stu(req);
        try {
            serv.updateStudent(stu);
        } catch (DaoExecption daoExecption) {
            daoExecption.printStackTrace();
            return false;
        }
        //更新session中的学生表为当前数据库的所有学生
        getAllStudents(req, res);
        System.out.println("com.cat.controler.AdminServlet : update student info successfully !");
        return true;
    }

}
